# coding=utf-8
from common.libs.NumberLibs import is_positive_int_zero
import re, math

def create_mysql_pages(page_size, query, values, full_path , key="p") :
    page_size = page_size
    query = query
    temp_page = values[key] if (key in values and values[key]) else 1
    if is_positive_int_zero(temp_page) :
        temp_page = int(temp_page) if int(temp_page) != 0 else 1
    else :
        temp_page = 1
    rule = "(&" + key + "=.*)"
    p_del = re.compile(rule, re.S)
    page_params = {
        'total': query.count(),
        'page_size': page_size,
        'page': temp_page,
        'url': p_del.sub("", full_path)
    }
    pager = query.paginate(temp_page, per_page=page_size, error_out=False)
    pages = mysql_paginator(page_params, pager)
    query_list = list(pager.items)
    return pages, query_list

def mysql_paginator( params, pager ):
    """
    自定义分页
    :param params:
    :return:
    """
    ret = {
        "is_prev": pager.has_prev, # 是否有上一页
        "is_next": pager.has_next, # 是否有下一页
        "current": pager.page, #当前页码
        "total_pages": pager.pages, #总页数
        "page_size": int(params['page_size']), #每页显示条数
        "total": int(params['total']), #总条数
        "prev_num" : pager.prev_num, #上一页页码数
        "next_num" : pager.next_num, #下一页页码数
        "url": params['url']
    }
    return ret